//
//  JMProductVC.m
//  NewiOSProject
//
//  Created by MAC on 2023/9/8.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMProductVC.h"
#import "JMProductCell.h"
#import "JMProductModel.h"
#import <YYLabel.h>
#import "JMTotalLoanVC.h"
#import "JMLoanApplySuccess.h"
#import "JMBubbleView.h"
#import "JMExtInfoManager.h"

@interface JMProductVC ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
{
    BOOL hasShowWindow;//是否提示过挽留弹窗
}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIView* headView;
@property (nonatomic, strong)UIView *footView;
@property (nonatomic, strong)UIImageView *topBgImgV;
@property (nonatomic, strong)UILabel *topLabel;//标题
@property (nonatomic, strong)UILabel *amountLabel;//产品额度
@property (nonatomic, strong)UIView *contentV;//顶部容器试图
@property (nonatomic, strong)UIView *progressContView;//进度条容器
@property (nonatomic, strong)UIView *progressView;//进度条
@property (nonatomic, strong)UIImageView *progressPointV;//进度指示器
@property (nonatomic, strong)UIView *pointCover;//扩大point手势区域

@property (nonatomic, strong)UILabel *progressStartLab;//开始额度
@property (nonatomic, strong)UILabel *progressEndLab;//最大额度

@property (nonatomic, strong)UIView *contentSubView;//额度底部容器
@property (nonatomic, strong)UILabel *usedQuotaLab;//使用的配额
@property (nonatomic, strong)UILabel *usedQuotaNumLab;//使用的配额
@property (nonatomic, strong)UILabel *residualQuotaLab;//剩余的配额
@property (nonatomic, strong)UILabel *residualQuotaNumLab;//剩余的配额
@property (nonatomic, strong)UIView *productPortfolioView;//产品组合（Mi cartera de productos）

@property (nonatomic, strong)JMLoadingButton *applyBtn;//现在申请按钮（Solicitar ahora）

@property (nonatomic, strong)UIButton *selBtn;//选择框

@property (nonatomic, strong)YYLabel *agreementLab;//协议 （He leído y estoy de acuerdo con 《Acuerdo de prestamo》）
@property (nonatomic, strong)UIButton *btn;//协议按钮《 Politica de privacidad 》
@property (nonatomic, assign)NSInteger selIndex;//协议按钮《 Politica de privacidad 》
@property (nonatomic, strong) NSArray *dataList;//原始数据
@property (nonatomic, strong) NSMutableArray *sortDataList;//筛选所有合适产品
@property (nonatomic, strong) NSMutableArray *sortedFieldValues;//筛选后产品的amount数组
@property (nonatomic, strong) JMProductPackageListModel *selModel;//筛选所有合适产品
@property (nonatomic, strong)UILabel *selValueLabel;//当前滑动的值
@property (nonatomic, assign) CGPoint startPoint;

@property (nonatomic, strong)NSTimer *timer;//当前滑动的值

@property (nonatomic, assign) NSTimeInterval time;
@property (nonatomic, strong)UILabel *gototalVCLab;//详情

@end

@implementation JMProductVC
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    };
}
// 开启定时器
- (void)startTimer {
    // 如果只有一张，直接放回，不需要开启定时器
//    if (_images.count <= 1) return;
    self.time = 60;
    // 如果定时器已经开启，则先停止再开启
    if (self.timer) [self stopTimer];
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(setBtn) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer fireDate];
}
// 关闭定时器
- (void)stopTimer {
    [self.timer invalidate];
    self.timer = nil;
}
-(void)setBtn{
    self.time -=1;
    if (self.time>0) {
        if (self.time<10) {
            [self.applyBtn setTitle:[NSString stringWithFormat:@"00:0%ld   Solicitar ahora",@(self.time).intValue] forState:(UIControlStateNormal)];
        }else{
            [self.applyBtn setTitle:[NSString stringWithFormat:@"00:%ld   Solicitar ahora",@(self.time).intValue] forState:(UIControlStateNormal)];
        }
    }else{
        [self stopTimer];
        [self.applyBtn setTitle:@"Solicitar ahora" forState:(UIControlStateNormal)];
    }
    
}
-(void)backBtnClick{
    if(hasShowWindow){
        [super backBtnClick];
    }else{
        [JMPublicAlertView showAlertWithFrame:(CGRectMake(0, 0, kAppW()-40, 166)) Title:@"" subTitle:@"Piense de nuevo, el límite de crédito seguirá aumentando！" BottomBtns:@[@"Confirmar"] Position:(JMPublicAlertViewPositionCenter) btnDirection:(JMPublicAlertViewButtonDirectionHor) btnActionBlock:^(NSInteger btnTag) {
            if (hasShowWindow) {
                [super backBtnClick];
            }else{
                hasShowWindow = YES;
            }
        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    产品打包【首页】：/api/index/product-packaging3
//    获取借款金额、周期、利息，管理费等信息：/api/loan/loan-apply-detail
//    获取首页需要的用户信用额度：/api/user/creditInfo
//    申请借款：/api/loan/apply2
//    检查是否上传扩展信息：/api/auth/check-ext-expired
//    上传扩展信息：/api/auth/ext-info
   
    self.TitleLabel.text = @"Cartera de crédito";
    self.TitleLabel.textColor = WhiteColor();

    self.fd_interactivePopDisabled = YES;
    JMExtInfoManager.sharedManager.vc = self;
    [JMExtInfoManager.sharedManager checkExtExpired];

    self.sortDataList = @[].mutableCopy;
    self.sortedFieldValues = @[].mutableCopy;
  
    [self.view addSubview:self.tableView];
    [self.view sendSubviewToBack:self.tableView];
    [self.view addSubview: self.footView];
    
    

    [self startTimer];
    [self.tableView reloadData];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.selIndex = -1;
    
    
    [self getDataList];
    //获取用户信用额度
    [[JMBaseRequest sharedInstance]requestBasePost:BasePostRequestUrl(@"/api/user/creditInfo") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {

       NSNumber *used =  dataDic[@"used"];
        NSNumber *unused = dataDic[@"unused"];
        NSNumber *total = dataDic[@"total"];
        _usedQuotaNumLab.text = used.stringValue.moneyString;
        _residualQuotaNumLab.text = unused.stringValue.moneyString;
//        _amountLabel.text =  total.stringValue.moneyString;
    } fail:^(NSString * _Nonnull errorMsg) {
    }];
    
    
    UIImageView *bgImgV = [[UIImageView alloc]initWithFrame:self.topBgImgV.frame];
    [bgImgV setImage:ImageNamed(@"bj-5")];
    [self.NavImg addSubview:bgImgV];
    self.NavImg.clipsToBounds = YES;
    [self.NavImg sendSubviewToBack:bgImgV];
    [self.backBtn setImage:ImageNamed(@"ICON／zuo") forState:(UIControlStateNormal)];
}
//上传扩展信息
-(void)upload{
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/ext-info") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [self showMessage:@""];
    } fail:^(NSString * _Nonnull errorMsg) {
        
    }];
}

-(void)getDataList{
//    ● 调用产品打包【首页】接口，获取到金额的区域和金额对应的产品
    [self startAnimating: nil];
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/index/product-packaging3") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSArray *arr = dataDic;
        [self stopAnimating];
        if(arr != nil &&[arr isKindOfClass:NSArray.class] &&arr.count){
            self.dataList = [JMProductPackageListModel mj_objectArrayWithKeyValuesArray:dataDic];
            [self.sortDataList addObjectsFromArray:self.dataList];
            [self sortLitData];
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        [self stopAnimating];
    }];
}

//排序产品
-(void)sortLitData{
    // 创建排序描述符
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"amount" ascending:YES];
    
    // 执行排序
    NSArray *sortedArray = [self.sortDataList sortedArrayUsingDescriptors:@[sortDescriptor]];
    self.sortDataList = sortedArray;
    for (int i=0; i<sortedArray.count; i++) {
        JMProductPackageListModel *model = self.sortDataList[i];
        [self.sortedFieldValues addObject:model.amount];
    }
    
    self.selModel  =self.sortDataList.lastObject;
    [self stopAnimating];
    [self.headView removeFromSuperview];
    self.headView = nil;
    _tableView.tableHeaderView = self.headView;
    
    JMProductPackageListModel *maxModel = self.sortDataList.lastObject;
    JMProductPackageListModel *minModel = self.sortDataList.firstObject;
    _progressStartLab.text = [NSString stringWithFormat:@"$%@",minModel.amount.stringValue.moneyString];
    _progressEndLab.text = [NSString stringWithFormat:@"$%@",maxModel.amount.stringValue.moneyString];
    _amountLabel.text =  maxModel.amount.stringValue.moneyString;

    [self.tableView reloadData];
    
}
//MARK: -UITableViewDataSource UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    NSLog(@"%ld",self.selModel.ProductPackageList.count);
    return self.selModel.ProductPackageList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JMProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JMProductCell" forIndexPath:indexPath];
    if (indexPath.row < self.selModel.ProductPackageList.count) {
        JMProductModel *model = self.selModel.ProductPackageList[indexPath.row];
        model.isFold = !(self.selIndex==indexPath.row);
        model.row = indexPath.row;
        cell.model = model;
        cell.selectionStyle = 0;
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    JMProductModel *model = self.selModel.ProductPackageList[indexPath.row];
    CGFloat h =model.isFold?ScaleW(117):ScaleW(233);
    return h;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    ●产品区域点击后，调用获取借款金额、周期、利息，管理费，利率等信息接口，显示某个产品的完整信息，该区域再次点击可恢复折叠
    if(indexPath.row == self.selIndex){
        self.selIndex = -1;
    }else{
        self.selIndex = indexPath.row;
    }
    JMProductModel *model = self.selModel.ProductPackageList[indexPath.row];
    model.isFold = !(self.selIndex==indexPath.row);
    [self getDetailWithModel:model];
}
-(void)getDetailWithModel:(JMProductModel *)model{
    if(model.repaymentPlanTime == nil){
        NSDictionary *dict = @{
            @"applicationAmount":model.amount.stringValue,
            @"applicationTerm":model.term.stringValue,
            @"productId":model.id.stringValue,
            @"termUnit":model.termUnit.stringValue
        };
        
        // [self startAnimating:nil];
        [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/loan/loan-apply-detail") params:dict success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
            [self stopAnimating];
            JMProductModel *tempModel = self.selModel.ProductPackageList[model.row];
            tempModel.actualAmount = dataDic[@"actualAmount"];
            tempModel.repayTotalAmount = dataDic[@"repayTotalAmount"];
            tempModel.repaymentPlanTime = dataDic[@"repaymentPlanTime"];
            tempModel.iva = dataDic[@"iva"];
            tempModel.interestAmount = dataDic[@"interestAmount"];
            tempModel.adminAmount = dataDic[@"adminAmount"];
            [self.tableView reloadData];
        } fail:^(NSString * _Nonnull errorMsg) {
            [self stopAnimating];
        }];
    }else{
        [self.tableView reloadData];
    }
}
//MARK: -lazyLoad

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kAppW(), kAppH()-self.footView.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[JMProductCell class] forCellReuseIdentifier:@"JMProductCell"]; // 注册UITableViewCell
        _tableView.tableHeaderView  = self.headView;
        _tableView.separatorColor = UIColor.clearColor;
        _tableView.sectionHeaderTopPadding = 0;
        _tableView.backgroundColor = Hex_Str_COLOR(@"#ffffff");
    }
    return _tableView;
}
-(UIView *)headView{
    if(!_headView){
        _headView = [[UIScrollView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(),400+NAVIGATION_BAR_HEIGHT()))];
        [_headView addSubview:self.topBgImgV];
        _headView.layer.masksToBounds = NO;
        _headView.clipsToBounds = NO;
        [_headView addSubview:self.contentV];

        
        UILabel *title = [JMControl createLabelWithFrame:(CGRectMake(15, _contentV.bottom+17, 188, FontH(20))) Font:BoldFont(18) Text:@"Mi cartera de productos" color:Hex_Str_COLOR(@"#0F1511")];
        title.width = CalculateLabelWidth(20, title.font, title.text)+22;
        [_headView addSubview:title];
        title.textAlignment = 1;
        title.width = CalculateLabelWidth(30, BoldFont(18), title.text)+22;
        title.centerX = kAppW()/2;
        
        UIView *leftLie = [[UIView alloc]initWithFrame:(CGRectMake(0, 0, 24, 2))];
        leftLie.backgroundColor = Hex_Str_COLOR(@"#3C57F8");
        [_headView addSubview:leftLie];
        leftLie.right = title.left-11;
        leftLie.centerY = title.centerY;
        
        UIView *rightLie = [[UIView alloc]initWithFrame:(CGRectMake(0, 0, 24, 2))];
        rightLie.backgroundColor = Hex_Str_COLOR(@"#3C57F8");
        [_headView addSubview:rightLie];
        rightLie.left = title.right+11;
        rightLie.centerY = title.centerY;
        
        _headView.height = title.bottom+20;
        
    }
    return _headView;
}
-(UIImageView *)topBgImgV {
    if(!_topBgImgV){
        CGFloat hei = kAppW()*343/375.0+JF_TOP_SPACE();
        _topBgImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), hei))];
        [_topBgImgV setImage:ImageNamed(@"bj-5")];
    }
    return _topBgImgV;
}
-(UILabel *)topLabel{
    if(!_topLabel){
        _topLabel = [JMControl createLabelWithFrame:(CGRectMake(0, 40, _contentV.width, FontH(12))) Font:Font(12) Text:@"Cuota máxima($)" color:Hex_Str_COLOR(@"#666666")];
        _topLabel.textAlignment = 1;
    }
    return _topLabel;
}
-(UILabel *)amountLabel{
    if(!_amountLabel){
        _amountLabel = [JMControl createLabelWithFrame:(CGRectMake(0, _topLabel.bottom+20, _contentV.width, 40)) Font:fontWithWeight(40, UIFontWeightBold) Text:@"0" color:Hex_Str_COLOR(@"#222222") textAlignment:1 numberOfLine:0];
    }
    return _amountLabel;
}
-(UIView *)contentV{
    if(!_contentV){
        _contentV = [[UIView alloc]initWithFrame:(CGRectMake(24, NAVIGATION_BAR_HEIGHT()+16, kAppW()-48, 269))];
        _contentV.backgroundColor = GradientColorWithColor(_contentV.size, FXGradientChangeDirectionVertical, HexAlpha_Str_COLOR(@"#ffffff", 0.8), HexAlpha_Str_COLOR(@"#ffffff", 1));
        [_contentV setShadowAndCornerWithCornerRadius:8 shadowRadius:24 shadowColor:HexAlpha_Str_COLOR(@"#B453FF", 0.35) shadowOffset:(CGSizeMake(0, 8)) shadowOpacity:1 borderWidth:2 borderColor:WhiteColor()];

        [_contentV addSubview:self.topLabel];
        [_contentV addSubview:self.amountLabel];
        [_contentV addSubview:self.progressContView];
        [_contentV addSubview:self.progressPointV];
        [_contentV addSubview:self.pointCover];
        [_contentV addSubview:self.progressStartLab];
        [_contentV addSubview:self.progressEndLab];
        [_contentV addSubview:self.contentSubView];
//        [_contentSubView setRoundedCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight) radii:8];

        _contentV.height = _contentSubView.bottom;
    }
    return _contentV;
}
-(UIView *)progressContView{
    if(!_progressContView){
        _progressContView= [[UIView alloc]initWithFrame:(CGRectMake(24, _amountLabel.bottom+32, _contentV.width-48, 10))];
        _progressContView.layer.borderColor = Hex_Str_COLOR(@"#C5CDFD").CGColor;
        _progressContView.layer.borderWidth =1;
        _progressContView.backgroundColor = HexAlpha_Str_COLOR(@"#EBEBED", 1);
        _progressContView.cornerRadius = 4;
        [_progressContView addSubview:self.progressView];
        [_progressContView addSubview:self.progressPointV];
    }
    return _progressContView;
}
-(UIView *)progressView{
    if(!_progressView){
        _progressView= [[UIView alloc]initWithFrame:(CGRectMake(1,1, _progressContView.width-2, _progressContView.height-2))];
        _progressView.cornerRadius = 4;
        _progressView.backgroundColor = mainGradientColor(_progressView.size);
    }
    return _progressView;
}
- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    CGPoint translation = [gesture translationInView:self.progressContView];
    
    if (gesture.state == UIGestureRecognizerStateBegan) {
        self.startPoint = self.progressPointV.center;
    }
//    ● 刚进入页面滑动条最上边和最右边是这个用户可以使用的最大额度，滑动条左侧是返回data所有amout里边的最小值
//    ● 返回结构中的amout是打包额度，需要按照从小到大顺序随着进度条拖动展示产品列表，只需要平均分配进度即可，不需要按照具体金额计算进度条位置
//    ●返回的data本身是个数组，里边每个元素有对应的额度，以及额度下对应的产品，当你滑动到一个额度时，去数组里找小于等于这个额度最接近的元素以及展示对应的产品
    
    // 计算新的位置
    CGPoint newCenter = CGPointMake(self.startPoint.x + translation.x, self.startPoint.y);
    // 限制在progressContView的边界内
    newCenter.x = MAX(24, MIN(self.progressContView.frame.size.width + 24, newCenter.x));
    // 更新progressPointV和progressView的位置
    self.progressPointV.center = newCenter;
    self.pointCover.center = newCenter;

    CGRect progressFrame = self.progressView.frame;
    progressFrame.size.width = newCenter.x-24;
    self.progressView.frame = progressFrame;
    if (_progressView.width>0) {
        _progressView.backgroundColor = mainGradientColor(_progressView.size);
    }

    if(self.dataList.count){
        
        //1.获取进度条对应的amount值
    //   curValue = min + scale*(max-min)
        JMProductPackageListModel *minModel = self.sortDataList.firstObject;
        JMProductPackageListModel *maxModel = self.sortDataList.lastObject;
        CGFloat progressScale = self.progressView.width/self.progressContView.width;
        NSInteger curValue = minModel.amount.integerValue + @(progressScale*(maxModel.amount.intValue - minModel.amount.intValue)).integerValue;
        //2.查找最接近的位值，非下标
        NSInteger index = [self.sortedFieldValues indexOfObject:@(curValue) inSortedRange:NSMakeRange(0, self.sortedFieldValues.count) options:NSBinarySearchingInsertionIndex usingComparator:^(NSNumber *obj1, NSNumber *obj2) {
            return [obj1 compare:obj2];
        }];
       
        
        JMProductPackageListModel *closeModel = self.sortDataList[index];
        _amountLabel.text =  closeModel.amount.stringValue.moneyString;
        self.selModel = closeModel;
        self.selIndex = -1;
        [self.tableView reloadData];
        //    NSLog(@"当前进度为 %.2f",progressScale);
            NSLog(@"当前进度对应的进度条额度为%@",@(curValue));
            NSLog(@"第%ld个对象",index);
            NSLog(@"当前最接近进度条额度的产品amount为%@",closeModel.amount);
    }
    
   
}
- (UIImageView *)progressPointV{
    if(!_progressPointV){
        _progressPointV = [[UIImageView alloc]initWithFrame:(CGRectMake(_progressView.width, 0, 44, 44))];
        [_progressPointV setImage:ImageNamed(@"hua kuai an niu")];
        _progressPointV.centerY = _progressContView.centerY;
        _progressPointV.centerX = _progressView.right+24;
      
    }
    return _progressPointV;
}
-(UIView *)pointCover{
    if (!_pointCover) {
        _pointCover = [[UIView alloc]initWithFrame:(CGRectMake(0, 0, 50, 50))];
        _pointCover.center = _progressPointV.center;
        // 添加拖拽手势
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        panGesture.delegate = self;
        [_pointCover addGestureRecognizer:panGesture];
    }
    return _pointCover;
}
-(UILabel *)progressStartLab{
    if(!_progressStartLab){
        _progressStartLab = [JMControl createLabelWithFrame:(CGRectMake(_progressContView.left, _progressContView.bottom+14, _progressContView.width, FontH(14))) Font:Font(14) Text:@"$0" color:Hex_Str_COLOR(@"#999999")];
        
    }
    return _progressStartLab;
}

-(UILabel *)progressEndLab{
    if(!_progressEndLab){

        _progressEndLab = [JMControl createLabelWithFrame:(CGRectMake(_progressContView.left, _progressContView.bottom+14, _progressContView.width, FontH(14))) Font:Font(14) Text:@"$0" color:Hex_Str_COLOR(@"#999999")];
        _progressEndLab.textAlignment =  2;
    }
    return _progressEndLab;
}
-(UIView *)contentSubView{
    if(!_contentSubView){
        _contentSubView = [[UIView alloc]initWithFrame:(CGRectMake(0, _contentV.height-69, _contentV.width, 69))];

        [_contentSubView setRoundedCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight) radii:8];
        _contentSubView.backgroundColor = GradientColorWithColor(_contentV.size, FXGradientChangeDirectionHorizontal, HexAlpha_Str_COLOR(@"#3C57F8", 1), HexAlpha_Str_COLOR(@"#C47EFA", 1));
        _contentSubView.layer.borderColor = WhiteColor().CGColor;
        _contentSubView.layer.borderWidth = 2;
        [_contentSubView addSubview:self.usedQuotaNumLab];
        [_contentSubView addSubview:self.usedQuotaLab];
        
        UIView *lineV = [[UIView alloc]initWithFrame:(CGRectMake(_contentSubView.width/2, 0, 1, 24))];
        lineV.centerY = _contentSubView.height/2;
        lineV.backgroundColor = WhiteColor();
        [_contentSubView addSubview:lineV];
        
        [_contentSubView addSubview:self.residualQuotaNumLab];
        [_contentSubView addSubview:self.residualQuotaLab];
    }
    return _contentSubView;
}
-(UILabel *)usedQuotaNumLab{
    if(!_usedQuotaNumLab){
        _usedQuotaNumLab = [JMControl createLabelWithFrame:(CGRectMake(24, 12, _contentSubView.width/2, FontH(17))) Font:BoldFont(16) Text:@"$0" color:Hex_Str_COLOR(@"#ffffff")];
    }
    return  _usedQuotaNumLab;
}
-(UILabel *)usedQuotaLab{
    if(!_usedQuotaLab){
        _usedQuotaLab = [JMControl createLabelWithFrame:(CGRectMake(_usedQuotaNumLab.left, _usedQuotaNumLab.bottom+8, _usedQuotaNumLab.width, FontH(12))) Font:Font(12) Text:@"Cuota utilizada($)" color:Hex_Str_COLOR(@"#ffffff")];
    }
    return _usedQuotaLab;
}

-(UILabel *)residualQuotaNumLab{
    if(!_residualQuotaNumLab){
        _residualQuotaNumLab = [JMControl createLabelWithFrame:(CGRectMake(_usedQuotaLab.right, _usedQuotaNumLab.top, _usedQuotaNumLab.width, FontH(17))) Font:BoldFont(16) Text:@"$0" color:Hex_Str_COLOR(@"#ffffff")];
    }
    return  _residualQuotaNumLab;
}
-(UILabel *)residualQuotaLab{
    if(!_residualQuotaLab){
        _residualQuotaLab = [JMControl createLabelWithFrame:(CGRectMake(_residualQuotaNumLab.left, _usedQuotaLab.top, _residualQuotaNumLab.width, FontH(12))) Font:Font(12) Text:@"Cuota restante($)" color:Hex_Str_COLOR(@"#ffffff")];
    }
    return _residualQuotaLab;
}


-(UIView *)footView{
    if(!_footView){
        _footView = [[UIView alloc]initWithFrame:(CGRectMake(0, kAppH()-ScaleW(310), kAppW(), ScaleW(310)))];
        _footView.backgroundColor = WhiteColor();
        _footView.layer.shadowColor = HexAlpha_Str_COLOR(@"#000000", 0.1).CGColor;
        _footView.layer.shadowRadius = 16;
        _footView.layer.shadowOpacity = 1;
        
        [_footView addSubview:self.gototalVCLab];
        [_footView addSubview:self.applyBtn];
        [_footView addSubview:self.selBtn];
        [_footView addSubview:self.agreementLab];
        [_footView addSubview:self.btn];
        _footView.height = _btn.bottom+JF_BOTTOM_SPACE()+30;
        _footView.top = kAppH() - _footView.height;
    }
    return _footView;
}
-(UILabel *)gototalVCLab{
    if(!_gototalVCLab){
        _gototalVCLab = [JMControl createLabelWithFrame:(CGRectMake(24, 10,kAppW()-48, 24)) Font:Font(15) Text:@"Ver detalles del préstamo>" color:mainSchemeColor()];
        _gototalVCLab.textAlignment = 2;
        @weakify(self);
        [_gototalVCLab tapAction:^(UIView *sender) {
            @strongify(self);
            if(self.dataList.count){
                JMTotalLoanVC *VC = JMTotalLoanVC.new;
                VC.productModel= self.selModel;
                [self.navigationController pushViewController:VC animated:YES];
            }
        }];
       
    }
    return _gototalVCLab;
}
-(JMLoadingButton *)applyBtn{
    if(!_applyBtn){
        _applyBtn = [[JMLoadingButton alloc]initWithFrame:(CGRectMake(24, _gototalVCLab.bottom+24, kAppW()-48, 56)) title:@"01:00   Solicitar ahora" font:mediumFont(17) titleLabelColor:Button_ENABLE_TEXTCOLOR() backgoundColor:Button_ENABLE_BG_COLOR() action:@selector(applyBtnBtnClick) target:self];
        _applyBtn.cornerRadius = 28;
        _applyBtn.enable = NO;
    }
    return _applyBtn;
}

-(void)applyBtnBtnClick{
    if(self.dataList.count==0){
        return;
    }
    NSMutableArray *arr = @[].mutableCopy;
    for (JMProductModel *mod in self.selModel.ProductPackageList) {
        NSDictionary *dict = @{
            @"applyAmount":mod.amount.stringValue,
            @"isReloan":mod.isReloan.intValue?@"1":@"0",
            @"productId":mod.id.stringValue,
            @"term":mod.term.stringValue,
            @"termUnit":mod.termUnit.stringValue
        };
        [arr addObject:dict];
    }
    NSDictionary *param=@{@"gwApplyReqList":arr};

    [JMCommonMethod uploadStatistics:@"Products" actionType:@"Apply_Loan_Click" parameters:nil];//@{@"productAndRanks":productAndRanks}
 
    [JMBaseRequest.sharedInstance requestBasePost:BasePostRequestUrl(@"/api/loan/apply2") params:param successResult:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSDictionary *data = dataDic[@"data"];
        NSString *code = dataDic[@"code"];
        NSString *message = dataDic[@"message"];
        [JMCommonMethod uploadStatistics:@"Products" actionType:@"Apply_Loan_Success" parameters:nil];//@{@"productAndRanks":productAndRanks}

        BOOL showStartV = [dataDic[@"data"] boolValue];
        JMLoanApplySuccess *vc = JMLoanApplySuccess.new;
        vc.showStart = showStartV;
        [self.navigationController pushViewController:vc animated:YES];
        [[NSNotificationCenter defaultCenter]postNotificationName:kNotiLivenessLoanSuccess object:nil];

    } fail:^(NSString * _Nonnull errorMsg) {
    }];
}
-(UIButton *)selBtn{
    if(!_selBtn){
        _selBtn = [JMControl createButtonWithFrame:(CGRectMake(24, _applyBtn.bottom+20, 24, 24)) ImageName:@"ICON／fuxuan 1" selectedImage:@"ICON／fuxuan" Target:self Action:@selector(selBtnClick) Title:nil tag:1];
    }
    return _selBtn;
}
-(void)selBtnClick{
    _selBtn.selected = !_selBtn.isSelected;
    _applyBtn.enable = _selBtn.selected;

}
-(YYLabel *)agreementLab{
    if(!_agreementLab){
        //协议
        _agreementLab = [[YYLabel alloc]initWithFrame:(CGRectMake(_selBtn.right+12, self.applyBtn.bottom+20,kAppW()-38, FontH(13)))];
        _agreementLab.numberOfLines = 0;
        _agreementLab.centerY = _selBtn.centerY;

        NSString *agreementStr =@"He leido y estoy de acuerdo con 《Acuerdo de prestamo》";
        NSDictionary *attributes = @{NSFontAttributeName:Font(10), NSForegroundColorAttributeName: Hex_Str_COLOR(@"#999999")};
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:agreementStr attributes:attributes];
        
        NSRange range0 = [agreementStr rangeOfString:@"He leido y estoy de acuerdo con"];
        @weakify(self)
        [text yy_setTextHighlightRange:range0 color:Hex_Str_COLOR(@"#9B9B9B") backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            @strongify(self)
            [self selBtnClick];
        }];
        
        NSDictionary *attributes1 = @{NSFontAttributeName:mediumFont(10), NSForegroundColorAttributeName: mainSchemeColor()};
        NSRange range = [agreementStr rangeOfString:@"《Acuerdo de prestamo》"];
        [text addAttributes:attributes1 range:range];
        [text yy_setTextHighlightRange:range color:Agreement_Text_COLOR() backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(loginLoanAgreement) andTitle:@"Acuerdo de prestamo"];
        }];
        _agreementLab.attributedText = text;
        
    }
    return _agreementLab;
}
-(UIButton *)btn{
    if(!_btn){
        _btn = [JMControl createButtonWithFrame:(CGRectMake(0, _agreementLab.bottom+30, kAppW(), FontH(15))) Target:self Action:@selector(politicaBtnClick) Title:@"《Politica fr privacidad》" titlColor:Hex_Str_COLOR(@"#222222") font:Font(15) tag:1 backgroundColor:nil];
    }
    return _btn;
}
-(void)politicaBtnClick{
    [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(loginPrivacyAgreement) andTitle:@"Politica de privacidad"];
}

-(void)dealloc{
    [self stopTimer];
}


@end

